package cn.tedu.egarticle1.Controller;

import cn.tedu.egarticle1.base.response.JsonResult;
import cn.tedu.egarticle1.base.response.StatusCode;
import cn.tedu.egarticle1.mapper.UserMapper;
import cn.tedu.egarticle1.pojo.dto.UserArticleParam;
import cn.tedu.egarticle1.pojo.dto.UserLoginParam;
import cn.tedu.egarticle1.pojo.entity.Article;
import cn.tedu.egarticle1.pojo.vo.ArticleVO;
import cn.tedu.egarticle1.pojo.vo.UserVO;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Api(tags="用户管理模块")
@Slf4j
@Validated
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    UserMapper userMapper;
    @PostMapping("login")
    @ApiOperation("用户登录")
    @ApiOperationSupport(order=20)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session){
        log.debug("userLoginParam="+userLoginParam);
        UserVO userVO = userMapper.selectUsernameAndPassword(userLoginParam);
        if(userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.ok(userVO);
    }
    @PostMapping("article")
    @ApiOperation("发表文章")
    @ApiOperationSupport(order=30)
    public JsonResult Addarticle(@Validated @RequestBody UserArticleParam userArticleParam, @ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        if(userVO == null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        Article Article = new Article();
        BeanUtils.copyProperties(userArticleParam,Article);
        Article.setUserId(userVO.getId());
        userMapper.insertArticle(Article);
        return JsonResult.ok();
    }
    @GetMapping("selectByArticleId")
    @ApiOperation("根据文章id查询文章")
    @ApiOperationSupport(order=40)
    public JsonResult selectByArticleId(@Range(min = 1,max=100,message ="文章id在1-100之间")@RequestParam Long id){
        ArticleVO ArticleVO = userMapper.selectByArticleId(id);
        return JsonResult.ok(ArticleVO);
    }
}
